package logic

import (
	"context"
	"errors"
	"log"
	"user_srv/cache"
	"user_srv/models"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var u models.User
	u.Mobile = in.Mobile
	err := u.GetUserByMobile()
	if err != nil {
		logx.Error("登录失败:查找手机号是否存在错误", err)
		return nil, err
	}

	get := cache.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if get.Val() != in.Sms {
		logx.Error("登录失败:", errors.New("验证码错误"))
		return nil, errors.New("验证码错误")
	}

	if u.ID > 0 {
		log.Println("账号存在,进行登录")
	} else {
		log.Println("账号不存在,进行注册")
		u.Password = pkg.Md5(in.Mobile)
		err = u.Register()
		if err != nil {
			logx.Error("登录失败:注册账号失败", err)
			return nil, err
		}
	}

	return &user.LoginResponse{UserId: int64(u.ID)}, nil
}
